//
//  BillFMDBHelper.swift
//  LGMusic
//
//  Created by 梁尚嘉 on 2017/3/31.
//  Copyright © 2017年 LimeGah. All rights reserved.
//

import UIKit
import FMDB
class BillFMDBHelper: FMDBHelper {
    
    class func billTableName() -> String {
        return "BILL_TABLE"
    }

    class func checkBillTable (_ dataBase:FMDatabase) -> Bool
    {
        let SQL = "CREATE TABLE IF NOT EXISTS "+self.billTableName()+" (author text NOT NULL,pic_big text NOT NULL,rank_change integer,charge integer,rank text NOT NULL,lrclink text NOT NULL,pic_small text NOT NULL,hot integer,has_mv integer,all_artist_ting_uid text NOT NULL,publishtime text NOT NULL,artist_name text NOT NULL,file_duration float,artist_id text NOT NULL,album_id text NOT NULL,style text NOT NULL,album_title text NOT NULL,album_no integer,song_id text NOT NULL,ting_uid text NOT NULL,all_artist_id text NOT NULL,title text NOT NULL,language text NOT NULL);"
        do {
            try dataBase.executeUpdate(SQL, values: nil)
            return true
        }catch {
            print(error)
            return false
        }
    }

    class func updateBillTable(_ bill:Bill,
                               isFavorite:Bool,
                               block:@escaping ((_ success:Bool)->Swift.Void)
        ) {

        self.FMDBQueue().inTransaction({ (db, rollback) in

            do {
                if self.checkBillTable(db!) {
                    if isFavorite {

                        try db?.executeUpdate("INSERT INTO "+self.billTableName()+" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                              values: [
                                                bill.author as Any,
                                                bill.pic_big as Any,
                                                bill.rank_change as Any,
                                                bill.charge as Any,
                                                bill.country as Any,
                                                bill.piao_id as Any,
                                                bill.rank as Any,
                                                bill.lrclink as Any,
                                                bill.pic_small as Any,
                                                bill.hot as Any,
                                                bill.has_mv as Any,
                                                bill.all_artist_ting_uid as Any,
                                                bill.publishtime as Any,
                                                bill.artist_name as Any,
                                                bill.file_duration as Any,
                                                bill.artist_id as Any,
                                                bill.album_title as Any,
                                                bill.album_no as Any,
                                                bill.song_id as Any,
                                                bill.ting_uid as Any,
                                                bill.all_artist_id as Any,
                                                bill.title as Any,
                                                bill.language as Any
                            ])
                    }else {
                        try db?.executeUpdate("DELETE FROM "+self.billTableName()+" where song_id="+bill.song_id!, values: nil)
                    }

                    block(true)
                }else {
                    block(false)
                }
            } catch {
                block(false)
                rollback?.pointee = true
                print(error)
            }

        })

    }


    class func getFavoriteBills(_ block:@escaping ((_ bills:[Bill])->Void)) {

        self.FMDBQueue().inTransaction({ (db, rollback) in
            do {
                if self.checkBillTable(db!) {
                    let result = try db?.executeQuery("SELECT * FROM "+self.billTableName(), values: nil)
                    var resultArray = [Bill]()
                    while (result?.next())! {
                        let jsonData = try JSONSerialization.data(withJSONObject: result?.resultDictionary()!, options: JSONSerialization.WritingOptions.prettyPrinted)
                        let jsonString = String.init(data: jsonData, encoding: String.Encoding.utf8)
                        resultArray.append(Bill.deserialize(from: jsonString)!)
                    }
                    block(resultArray)
                }else {
                    block([])
                }
            } catch {
                block([])
                rollback?.pointee = true
                print(error)
            }
        })
    }
}
